﻿using System.Collections.Generic;
using System.Configuration;
using Microsoft.Web.Administration;
using Microsoft.Web.Management.Server;

namespace LeastPrivilege.CustomBasicAuthentication.Management
{
	class UnregisteredAuthenticationModuleService : ConfigurationAuthenticationModuleService
	{
		private UnregisteredAuthenticationSection _config;

		public UnregisteredAuthenticationSection Configuration
		{
			get
			{
				if (_config == null)
				{
					_config = (UnregisteredAuthenticationSection)ConfigurationManager.GetSection(UnregisteredAuthenticationSection.SectionName);
				}

				return _config;
			}
		}

		protected override string EnabledPropertyName
		{
			get { return "enabled"; }
		}

		protected override string SectionName
		{
			get { return UnregisteredAuthenticationSection.SectionName; }
		}

		[ModuleServiceMethod(PassThrough = true)]
		public Dictionary<string, string> GetConfiguration()
		{
			var config = new Dictionary<string, string>();
			config.Add("realm", Configuration.Realm);
			config.Add("providerName", Configuration.ProviderName);
			config.Add("cachingEnabled", Configuration.CachingEnabled.ToString());
			config.Add("cachingDuration", Configuration.CachingDuration.ToString());
			config.Add("requireSSL", Configuration.RequireSSL.ToString());
			return config;
		}

		[ModuleServiceMethod(PassThrough = true)]
		public Dictionary<string, string> GetEnabled()
		{
			var config = new Dictionary<string, string>();
			config.Add("enabled", Configuration.Enabled.ToString());
			//config.Add("isLocked", Configuration.IsLocked.ToString());
			config.Add("isLocked", "true");
			return config;
		}

		[ModuleServiceMethod(PassThrough = true)]
		public void SetConfiguration(Dictionary<string, string> updatedValues)
		{
			Configuration.Realm = updatedValues["realm"];
			Configuration.ProviderName = updatedValues["providerName"];
			Configuration.CachingEnabled = bool.Parse(updatedValues["cachingEnabled"]);
			Configuration.CachingDuration = int.Parse(updatedValues["cachingDuration"]);
			Configuration.RequireSSL = bool.Parse(updatedValues["requireSSL"]);
		}

		[ModuleServiceMethod(PassThrough = true)]
		public void SetEnabled(bool enabled)
		{
			Configuration.Enabled = enabled;

			base.ManagementUnit.Update();
		}
	}
}